package com.myblog.myblog.service.impl;

import cn.hutool.core.util.IdUtil;
import com.myblog.myblog.constant.Constant;
import com.myblog.myblog.domain.TaskJob;
import com.myblog.myblog.mapper.TaskJobMapper;
import com.myblog.myblog.service.TaskJobService;
import com.myblog.myblog.utils.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * @author gyl
 * @data 2020/5/5 15:02
 */
@Service("TaskJobService")
public class TaskJobServiceImpl implements TaskJobService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private TaskJobMapper taskJobMapper;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init(){
        List<TaskJob> TaskJobList = taskJobMapper.selectAll();
        for(TaskJob taskJob : TaskJobList){
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, taskJob.getId());
            //如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createTaskJob(scheduler, taskJob);
            }else {
                ScheduleUtils.updateTaskJob(scheduler, taskJob);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(TaskJob taskJob) {
        taskJob.setId(IdUtil.simpleUUID());
        taskJob.setCreateTime(new Date());
        taskJob.setStatus(Constant.NORMAL+"");
        taskJobMapper.insert(taskJob);
        ScheduleUtils.createTaskJob(scheduler, taskJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TaskJob taskJob) {
        ScheduleUtils.updateTaskJob(scheduler, taskJob);
        taskJobMapper.updateByPrimaryKeySelective(taskJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(String jobId) {
        ScheduleUtils.run(scheduler, taskJobMapper.selectByPrimaryKey(jobId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(String jobId) {
        ScheduleUtils.pauseJob(scheduler, jobId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(String jobId) {
        ScheduleUtils.resumeJob(scheduler, jobId);
    }

}